//
//  FSUpDoingReceiveController.m
//  WZSOA
//
//  Created by 刘沿 on 16/6/3.
//  Copyright © 2016年 刘沿. All rights reserved.
//

#import "FSUpDoingReceiveController.h"
#import "GDataDefines.h"

@interface FSUpDoingReceiveController ()
//当前页
@property (nonatomic,assign)NSInteger currentPage;

//获取的条数
@property (nonatomic,assign)NSInteger totalCounts;

//存放数据的数组
@property (nonatomic,strong)NSMutableArray *dataArray;
@end

@implementation FSUpDoingReceiveController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"refreshOADetailData" object:nil];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    __weak typeof (self) weakSelf = self;
    
    
    // 添加一个头部的刷新控件
    
    
    [self.tableView addHeaderWithCallback:^{
        
        weakSelf.currentPage = 1;
        
        [weakSelf loadData];
        
        
    }];
    
    //主动让下拉刷新头部控件进入刷新状态
    [self.tableView headerBeginRefreshing];
    
    //    添加一个尾部的刷新控件
    
    [self.tableView addFooterWithCallback:^{
        
        if ((self.currentPage - 1) * KPageSize < self.totalCounts) {
            
            [weakSelf loadMore];
        }else {
            
            [weakSelf.tableView footerEndRefreshing];
            [weakSelf.view makeToast:@"没有更多了"];
        }
        
    }];
    
}
-(void)refreshData{
    
    self.currentPage = 1;
    [self loadData]; //加载网络数据
}

#pragma mark-------加载网络数据

//加载数据
- (void)loadData{

    NSString *userID = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    
    NSArray *array = @[@{@"userID":userID},@{@"page":[NSString stringWithFormat:@"%ld",self.currentPage]}];

    NSString *method = nil;
    
    if (self.type == UpToReceive) {
        //待办收文
        
        method = KTodoSwPageMethod;
        
    }else {
    //待办发文
        method = KTodoFwPageMethod;
    
    }

    [HttpTools postWithURL:KexchpageURL arrays:array method:method success:^(id JSON) {
        
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
        
        self.dataArray = [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
        
        [self.tableView reloadData];
        
        [self.tableView headerEndRefreshing];
        
        self.currentPage ++;
        
        if (self.dataArray.count == 0) {
            
            [self.view makeToast:@"暂时还没有代办工作哦"];
            
        }
        
    } failure:^(NSError *error) {
        
        NSLog(@"%@",error);
        
    }];

}


//加载更多数据
- (void)loadMore{
    NSString *userID = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    
    NSArray *array = @[@{@"userID":userID},@{@"page":[NSString stringWithFormat:@"%ld",self.currentPage]}];
    
    NSString *method = nil;
    
    if (self.type == UpToReceive) {
        //待办收文
        
        method = KTodoSwPageMethod;
        
    }else {
        //待办发文
        method = KTodoFwPageMethod;
        
    }

    [HttpTools postWithURL:KexchpageURL arrays:array method:method success:^(id JSON) {
        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        self.currentPage++;
        [self.tableView footerEndRefreshing];
    } failure:^(NSError *error) {
        [self.tableView footerEndRefreshing];
    }];

}

#pragma mark-----解析服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            FSReceiveModel* model = [[FSReceiveModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"接收时间"] objectAtIndex:0];
            GDataXMLElement * nameElement = [[data elementsForName:@"上一办理人"] objectAtIndex:0];
            GDataXMLElement * stateElement = [[data elementsForName:@"公文状态"] objectAtIndex:0];
            GDataXMLElement * formElement = [[data elementsForName:@"表单"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.name = [nameElement stringValue];
            model.state = [stateElement stringValue];
            model.form = [formElement stringValue];
            model.fileId = [fileIdElement stringValue];
            [array addObject:model];
        }
    }
    
    //获取根节点下的数据
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue];
    }
    
    self.title = [NSString stringWithFormat:@"待办工作(%lu)",(unsigned long)self.totalCounts];
    
    return array;
}

#pragma mark-------数据源和代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *ReuseIdentifier = @"Cell";
    
    FSUpDoingReceiveCell *cell = [tableView dequeueReusableCellWithIdentifier:ReuseIdentifier];
    if (cell == nil) {
        
        cell = [FSUpDoingReceiveCell UpDoingReceiveCell];
    }
    cell.receiveModel = self.dataArray[indexPath.row];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    FSReceiveModel *model = self.dataArray[indexPath.row];
    
    CGFloat titleFloat = [FSHightTool heightbyString:model.title font:20 minsWidth:60];
    NSString *desstring = [NSString stringWithFormat:@"%@/%@/%@",model.time,model.state,model.name];
    
    CGFloat desfloat = [FSHightTool heightbyString:desstring font:14 minsWidth:60];

    return titleFloat + desfloat + 20;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    FSReceiveModel *model = self.dataArray[indexPath.row];

    if (self.detailBlock) {
        
        self.detailBlock(indexPath.row,model.fileId,model.isEditor,model.form);
        
    }
    
}




@end






















